package com.hamishmedlin.psxpw;

public class QEncoder {

	public static String encodePassword(FormData formData){
		
		int i,bit;
		
		for(i=0;i<10;i++){			
			QGlobals.passwordData[i] = 0;
		}
		
		int nextmap = formData.getNextMap();
		int gameskill = formData.getGameSkill();
		
		QGlobals.passwordData[0] = (nextmap & 62) >> 1;
		QGlobals.passwordData[1] = ((nextmap & 1) << 4) | ((gameskill & 3) << 2);
		
		if(formData.getChecked(QGlobals.BACKPACK)){
			QGlobals.passwordData[1] |= 2;
		}
		
		if(formData.getChecked(QGlobals.WEAPON_CHAINSAW)){
			QGlobals.passwordData[1] |= 1;
		}
		
		if(formData.getChecked(QGlobals.WEAPON_BFG)){
			QGlobals.passwordData[2] |= 16;
		}
		
		if(formData.getChecked(QGlobals.WEAPON_PLASMA)){
			QGlobals.passwordData[2] |= 8;
		}
		
		if(formData.getChecked(QGlobals.WEAPON_ROCKET)){
			QGlobals.passwordData[2] |= 4;
		}
		
		if(formData.getChecked(QGlobals.WEAPON_CHAINGUN)){
			QGlobals.passwordData[2] |= 2;
		}
		
		if(formData.getChecked(QGlobals.WEAPON_SSG)){
			QGlobals.passwordData[2] |= 1;
		}
		
		if(formData.getChecked(QGlobals.WEAPON_SHOTGUN)){
			QGlobals.passwordData[3] |= 16;
		}
		
		//clip
		bit = encodePassItem(formData.getClip(),formData.getMaxAmmo(QGlobals.MAX_AMMO_CLIP));		
		QGlobals.passwordData[3] |= (bit & 15);
		
		//shell
		bit = encodePassItem(formData.getShell(),formData.getMaxAmmo(QGlobals.MAX_AMMO_SHELL));
		QGlobals.passwordData[4] |= (bit & 15) << 1;
		
		//cell
		bit = encodePassItem(formData.getCell(),formData.getMaxAmmo(QGlobals.MAX_AMMO_CELL));
		QGlobals.passwordData[4] |= (bit & 8) >> 3;
		QGlobals.passwordData[5] |= (bit & 7) << 2;
		
		//rocket
		bit = encodePassItem(formData.getRockets(),formData.getMaxAmmo(QGlobals.MAX_AMMO_ROCKET));
		QGlobals.passwordData[5] |= (bit & 12) >> 2;
		QGlobals.passwordData[6] |= (bit &  3) << 3;
		
		//health
		bit = encodePassItem(formData.getHealth(),200);
		QGlobals.passwordData[6] |= (bit & 14) >> 1;
		QGlobals.passwordData[7] |= (bit &  1) << 4;
		
		//armor
		bit = encodePassItem(formData.getArmor(),200);
		QGlobals.passwordData[7] |= (bit & 15);
		
		//armortype
		QGlobals.passwordData[8] |= formData.getArmorType();
		
		// determine encryption key
		for(i = 0; i < 9; i++){
			QGlobals.passwordData[9] ^= QGlobals.passwordData[i];
		}
		
		// encrypt
		for(i = 0; i < 9; i++){
			QGlobals.passwordData[i] ^= QGlobals.passwordData[9];
		}
		
		return displayPassword();
	}
	
	
	private static String displayPassword(){
		String outputStr = "";
		
		for(int i = 0; i < QGlobals.passwordData.length;i++){
			outputStr += QGlobals.passwordChar.charAt(QGlobals.passwordData[i]);
		}
		
		return outputStr.toUpperCase();
	}
	
	
	private static int encodePassItem(int value,int maxvalue){
		int bit;
		value = value << 3;
		bit = QUtils.intDivide(value, maxvalue);
		
		if(QUtils.intMod(value, maxvalue) != 0)
			bit++;
		
		return bit;
	}
}
